import * as css from "./index.css";
import * as tf from "@tensorflow/tfjs";
import Konva from "konva";
import Tesseract from "tesseract.js";
import "@tensorflow/tfjs-backend-webgl";
import { loadGraphModel } from "@tensorflow/tfjs-converter";
import { nms, postprocess_boxes } from "../../utils/processResult";
import * as React from "react";
import { draw } from "../draw";
import { init, recognize } from "../../utils/recogize";
// const tesseractWorker = initTesseract();
export default class App {
  constructor(elem) {
    if (!elem) return;
    this.elem = elem;

    this.init();
    // var a = tf.tensor([1]);
    // var b = tf.tensor([2]);
    // console.log(tf.add(a, b));
  }

  async init() {
    const MODEL_URL = "http://localhost:9000/web_model_yolo/model.json";
    const model = await loadGraphModel(MODEL_URL);
    const modelPromise = init();

    const cat = tf.browser.fromPixels(document.getElementById("cat"));
    // console.log([cat, cat]);
    const cat1 = cat.expandDims().cast("float32").div(255);
    // const cat2 = tf.transpose(cat1, [0, 2, 1, 3]);
    // cat.reshape([1, ...cat.shape]);
    const start = Date.now();
    console.log(model.outputNodes);

    model
      .executeAsync(
        {
          input_1: cat1,
        },
        ["Identity:0", "Identity_1:0"]
      )
      .then(async (outtensor) => {
        console.warn(
          "object recoginize duration : ",
          Date.now() - start,
          " ms"
        );
        console.log(outtensor);
        outtensor = outtensor.map((item) => {
          return tf.reshape(item, [-1, item.shape[item.shape.length - 1]]);
        });
        const pred_bbox = tf.concat(outtensor, 0);
        const _bboxes = await postprocess_boxes(pred_bbox);
        const bboxes = await nms(_bboxes);
        const layer = new Konva.Layer();

        const outputEl = document.getElementById("outputs");

        // add the shape to the layer
        bboxes.forEach((item, index) => {
          const dots = Array.prototype.slice.apply(item.dataSync(), [0, 4]);
          let x = Math.floor(dots[0]),
            y = Math.floor(dots[1]),
            width = Math.ceil(dots[2] - x),
            height = Math.ceil(dots[3] - y);
          const imgData = cat.slice([y, x], [height, width]);
          draw(outputEl, imgData);
          index == 5 &&
            recognize(modelPromise, imgData, (data) => {
              draw(outputEl, data, "alpha");
            });
          const poly = new Konva.Rect({
            x,
            y,
            width,
            height,
            stroke: "#00D2FF",
            closed: true,
          });
          layer.add(poly);
        });
        this.stage.add(layer);
        // const boxId = array[0][idIndex];
        // const boxName = array[0][nameIndex];
        // const [imgIdCropData, idShape] = crop(
        //   arr,
        //   boxId[0],
        //   boxId[2],
        //   partIdRef
        // );
        // const [imgNameCropData, nameShape] = crop(
        //   arr,
        //   boxName[0],
        //   boxName[2],
        //   partNameRef
        // );
        // const idStr = await cardIdRecog(imgIdCropData, idShape);
        // const nameStr = await cardNameRecog(imgNameCropData, nameShape);
        // stageRef.current?.add(layer);
        // partIdRef.current.querySelector("span").textContent = idStr;
        // partNameRef.current.querySelector("span").textContent = nameStr;
      });
  }

  initKonva() {
    var imgEl = document.getElementById("cat");
    imgEl.onload = (e) => {
      const imageObj = e.target;
      this.stage = new Konva.Stage({
        container: "container",
        width: imageObj.width,
        height: imageObj.height,
      });
    };
  }

  render() {
    const imgUrl = "/2.png";
    if (this.elem) {
      this.elem.innerHTML = `
        <section data-component="app">
        <img id="cat" src=${imgUrl} />
        <div id="container" style="position: absolute; top: 0" />
        </section>
        <ul id="outputs"> </ul>
        `;
      this.initKonva();
    }
  }
}
